package org.edu.modules.dorm.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.api.client.util.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.edu.common.api.vo.Result;
import org.edu.common.aspect.annotation.AutoLog;
import org.edu.common.system.base.controller.BaseController;
import org.edu.common.system.vo.LoginUser;
import org.edu.modules.dorm.entity.VeBaseCalendar;
import org.edu.modules.dorm.entity.VeDormSemester;
import org.edu.modules.dorm.entity.VeDormWsceil;
import org.edu.modules.dorm.entity.bo.BasicResponseBO;
import org.edu.modules.dorm.entity.bo.VeCampusBO;
import org.edu.modules.dorm.service.VeBaseCalendarService;
import org.edu.modules.dorm.service.VeBaseDormManageService;
import org.edu.modules.dorm.service.VeDormSemesterService;
import org.edu.modules.dorm.service.VeDormWsceilService;
import org.edu.modules.dorm.vo.VeBaseWeekVo;
import org.edu.modules.dorm.vo.VeDormCalendarVo;
import org.edu.modules.dorm.vo.VeDormWsceilExcelVO;
import org.edu.modules.dorm.vo.VeDormWsceilVo;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api(tags="卫生评比模块")
@RestController
@RequestMapping("dorm/wsceil")
@Slf4j
public class VeDormWsceilController extends BaseController<VeDormWsceil,VeDormWsceilService> {
    @Autowired
    private VeDormWsceilService veDormWsceilService;
    @Autowired
    private VeDormSemesterService veDormSemesterService;
    @Autowired
    private VeBaseCalendarService veBaseCalendarService;
    @Autowired
    private VeBaseDormManageService veBaseDormManageService; //李少君

    /**
     * 新增卫生获取日期学期
     */
    @ApiOperation(value = "新增卫生获取日期学期",notes = "新增卫生获取日期学期")
    @PostMapping("/addMessage")
    public Result<?> addMessage(){
        //返回页面中当前学期以及当前的周数
        VeDormCalendarVo veDormCalendarVo = veDormWsceilService.findNowDate();
        return Result.OK(veDormCalendarVo);
    }


    /**
     * 新增卫生
     */
    @AutoLog(value = "新增卫生评比")
    @ApiOperation(value = "新增卫生评比",notes = "新增卫生评比")
    @PostMapping("/add")
    public Result<?> addWsceil(@ApiParam(value = "校区ID") @RequestParam("campusId") Long campusId,
                               @ApiParam(value = "学期ID") @RequestParam("semId") Long semId,
                               @ApiParam(value = "周") @RequestParam("week") Integer week,
                               @ApiParam(value = "宿舍楼ID") @RequestParam("jzwId") Long jzwId,
                               @ApiParam(value = "楼层ID") @RequestParam("lcId") Long lcId,
                               @ApiParam(value = "宿舍ID") @RequestParam("ssId") Long ssId,
                               @ApiParam(value = "周一分数") @RequestParam("oneScore") Long oneScore,
                               @ApiParam(value = "周二分数") @RequestParam("twoScore") Long twoScore,
                               @ApiParam(value = "周三分数") @RequestParam("threeScore") Long threeScore,
                               @ApiParam(value = "周四分数") @RequestParam("fourScore") Long fourScore,
                               @ApiParam(value = "周五分数") @RequestParam("fiveScore") Long fiveScore,
                               @ApiParam(value = "月份") @RequestParam("mouth") Long mouth) {
        Integer check = veDormWsceilService.findWsceil(semId, week, ssId);
        if(check != 0){
            return Result.error("该宿舍本周已经评比过了！");
        }

        List<Long> list = new ArrayList<>();
        list.add(oneScore);
        list.add(twoScore);
        list.add(threeScore);
        list.add(fourScore);
        list.add(fiveScore);

        Boolean flag = veDormWsceilService.add(campusId,semId,week,jzwId,lcId,ssId,list,mouth);
        if(flag){
            return Result.OK("添加成功！");
        }
        return Result.error("添加失败！");
    }
    /**
     * 模糊查询宿舍卫生
     * @param
     * @return
     */
    @ApiOperation(value = "模糊查询宿舍卫生", notes = "模糊查询宿舍卫生")
    @PostMapping("/queryByName")
    public Result<?> queryByName (@ApiParam(value = "校区ID") @RequestParam("campusId" )String campusId,
                                  @ApiParam(value = "建筑物ID") @RequestParam("jzwId") String jzwId,
                                  @ApiParam(value = "楼层ID") @RequestParam("lcId") String lcId,
                                  @ApiParam(value = "宿舍ID") @RequestParam("ssId") String ssId,
                                  @ApiParam(value = "学期ID") @RequestParam("semId") String semId,
                                  @ApiParam(value = "周数") @RequestParam("weekNum") String weekNum) {
        Long campusid = campusId.equals("") ? null :Long.parseLong(campusId);
        Long jzwid = jzwId.equals("") ? null :Long.parseLong(jzwId);
        Long lcid = lcId.equals("") ? null :Long.parseLong(lcId);
        Long ssid = ssId.equals("") ? null :Long.parseLong(ssId);
        Long semid = semId.equals("") ? null :Long.parseLong(semId);
        Long weeknum = weekNum.equals("") ? null :Long.parseLong(weekNum);

//        BasicResponseBO<List> list1 = veBaseDormManageService.getSemesterMessage();//李少君
//        List<VeDormSemester> result = JSONObject.parseArray(JSON.toJSONString(list1.getResult()),VeDormSemester.class);
//        BasicResponseBO<List> list2 = veBaseDormManageService.getCampusMessage(); //李少君
//        List<VeCampusBO> result1 = JSONObject.parseArray(JSON.toJSONString(list2.getResult()),VeCampusBO.class);
//        List<VeDormWsceilVo> v = veDormWsceilService.queryWsceil(campusid, jzwid, lcid, ssid, semid, weeknum);
//        for(int i =0 ;i<v.size();i++){
//            for (int j =0 ;j<result.size();j++){
//                if(v.get(i).getSemId()==(result.get(j).getId().longValue())){
//                    v.get(i).setSemName(result.get(j).getXQMC());
//                }
//            }
//            for (int k =0 ;k<result1.size();k++){
//                if(v.get(i).getCampusId()==(result1.get(k).getId().longValue())){
//                    v.get(i).setCampusName(result1.get(k).getXqmc());
//                }
//            }
//        }

        List<VeDormWsceilVo> list = veDormWsceilService.queryWsceil(campusid, jzwid, lcid, ssid, semid, weeknum);
        return Result.OK(list);
    }

    /**
     * 查询学期
     * @param
     * @return
     */
    @ApiOperation(value = "查询学期",notes = "查询学期")
    @PostMapping("/semester")
    public Result<?> semester () {
        List<VeDormSemester> list = veDormSemesterService.getSemester();
//        BasicResponseBO<List> list = veBaseDormManageService.getSemesterMessage();//李少君
//        List<VeDormSemester> result = list.getResult();
        return Result.OK(list);
    }
    /**
     * 查询周数
     * @param
     * @return
     */
    @ApiOperation(value = "查询周数",notes = "查询周数")
    @PostMapping("/weekNum")
    public Result<?> weekNum ( @ApiParam(value = "学期Id")@RequestParam("semester")Long semester) {
//        QueryWrapper<VeBaseCalendar> wrapper = new QueryWrapper<>();
//        wrapper.eq("semId",semester);
//        List<VeBaseCalendar> list = veBaseCalendarService.list(wrapper);
        List<VeBaseCalendar> list = veBaseCalendarService.getCalendar(semester);
        List<VeBaseWeekVo> re = Lists.newArrayList() ;
        if( !CollectionUtils.isEmpty(list) ){
            Map<Integer,List<VeBaseCalendar>> map = list.stream()
                    .collect(Collectors.groupingBy(VeBaseCalendar::getWeek)) ;
            List<VeBaseWeekVo> finalRe = re;
            map.forEach((k, v)->{
                VeBaseWeekVo vo = new VeBaseWeekVo() ;
                vo.setWeek(k) ;
                v = v.stream().sorted(Comparator.comparing(VeBaseCalendar::getDates)).
                        collect(Collectors.toList()) ;
                String name = "第"+k+"周（"+v.get(0).getDates()+"-"+v.get(v.size()-1).getDates()+")" ;
                vo.setName(name) ;
                finalRe.add(vo) ;
            });
            re = finalRe.stream().sorted(Comparator.comparing(VeBaseWeekVo::getWeek)).
                    collect(Collectors.toList()) ;
        }
        return Result.OK(re);
    }


    /**
     * 通过Id获取编辑消息
     */
    @ApiOperation(value = "通过Id获取编辑消息",notes = "通过Id获取编辑消息")
    @PostMapping("/updateMessage")
    public Result<?> updateMessage ( @ApiParam(value = "卫生评比Id")@RequestParam("id")Long id) {
        List<VeDormWsceil> list = veDormWsceilService.updateMessage(id);
        return Result.OK(list);
    }

    /**
     * 根据Id进行修改
     */
    @AutoLog(value = "根据Id进行修改")
    @ApiOperation(value = "根据Id进行修改",notes = "根据Id进行修改")
    @PostMapping("/update")
    public Result<?> update(
            @ApiParam(value = "周一Id")@RequestParam("oneId")Long oneId,
            @ApiParam(value = "周二ID")@RequestParam("twoId")Long twoId,
            @ApiParam(value = "周三ID")@RequestParam("threeId")Long threeId,
            @ApiParam(value = "周四ID")@RequestParam("fourId")Long fourId,
            @ApiParam(value = "周五ID")@RequestParam("fiveId")Long fiveId,
            @ApiParam(value = "周一分数")@RequestParam("oneScore")Long oneScore,
            @ApiParam(value = "周二分数")@RequestParam("twoScore")Long twoScore,
            @ApiParam(value = "周三分数")@RequestParam("threeScore")Long threeScore,
            @ApiParam(value = "周四分数")@RequestParam("fourScore")Long fourScore,
            @ApiParam(value = "周五分数")@RequestParam("fiveScore")Long fiveScore){
        List<Long> idlist = new ArrayList<>();
        idlist.add(oneId);
        idlist.add(twoId);
        idlist.add(threeId);
        idlist.add(fourId);
        idlist.add(fiveId);
        List<Long> scoreList = new ArrayList<>();
        scoreList.add(oneScore);
        scoreList.add(twoScore);
        scoreList.add(threeScore);
        scoreList.add(fourScore);
        scoreList.add(fiveScore);
        Boolean flag = veDormWsceilService.update(idlist,scoreList);
        if(flag == true){
            return Result.OK("更改成功");
        }
        return Result.error("更改失败");

    }

    /**
     * 通过Id删除卫生评比
     * @param
     * @return
     */
    @ApiOperation(value = "通过Id删除卫生评比",notes = "通过Id删除卫生评比")
    @PostMapping("/delete")
    public Result<?> delete ( @ApiParam(value = "卫生评比ID")@RequestParam("id")Long id) {
        Boolean flag = veDormWsceilService.delete(id);
        if(flag == true){
            return Result.OK("删除成功");
        }
        return Result.error("删除失败");
    }

    /**
     * 本学期的卫生评比情况
     * @param
     * @return
     */
    @ApiOperation(value = "本学期的卫生评比情况",notes = "本学期的卫生评比情况")
    @PostMapping("/allWsceil")
    public Result<?> allWsceil ( @ApiParam(value = "宿舍ID")@RequestParam("ssId")Long ssId) {
        List<VeDormWsceilVo> list = veDormWsceilService.allWsceil(ssId);
        return Result.OK(list);
    }

    @AutoLog(value = "卫生评比信息导出excel模板")
    @ApiOperation(value = "卫生评比信息导出excel模板",notes = "卫生评比信息导出excel模板")
    @RequestMapping(value = "exportModel")
    public ModelAndView exportModel(){
        ModelAndView mv=new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "卫生评比信息列表");
        mv.addObject(NormalExcelConstants.CLASS, VeDormWsceilExcelVO.class);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        ExportParams exportParams = new ExportParams("卫生评比信息", "导出人:"+user.getRealname(), "导出信息");
        List<VeDormWsceilExcelVO> list = new ArrayList<>();
        VeDormWsceilExcelVO v = new VeDormWsceilExcelVO();
        v.setSemId("2021-2022上学期");
        v.setCampusId("北新1111111");
        v.setJzwId("学生公寓2");
        v.setLcId("2楼");
        v.setSsId("220");
        v.setScore(10L);
        v.setMouth(4l);
        v.setWeekNum(20L);
        v.setWeek(1L);
        list.add(v);
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
//        mv.addObject(NormalExcelConstants.DATA_LIST,  new ArrayList<VeDormWsceil>());
        mv.addObject(NormalExcelConstants.DATA_LIST,  list);
        return mv;
    }

    @AutoLog(value = "卫生评比信息导入excel表格")
    @ApiOperation(value = "卫生评比信息导入excel表格", notes = "卫生评比信息导入excel表格")
    @PostMapping(value = "import")
    public Result<?> excelImport(MultipartFile file) {
        ImportParams params = new ImportParams( );
        params.setTitleRows(2);
        params.setHeadRows(1);
        params.setNeedSave(true);
        try {
            List<VeDormWsceilExcelVO> list = ExcelImportUtil.importExcel(file.getInputStream(), VeDormWsceilExcelVO.class, params);
            int a = veDormWsceilService.excelImport(list);
            if(a==1){
                return Result.OK("文件导入成功！数据行数：" + list.size());
            }else if(a==0){
                return Result.error("导入失败，请检查所填数据是否存在!");
            }else {
                return Result.error("导入失败，导入的数据与已有数据重复!");
            }

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("文件导入失败:" + e.getMessage());
        } finally {
            try {
                file.getInputStream().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
